package org.ala.tcp_feign_server.context.login;

import java.util.LinkedList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.ala.tcp_feign_common.config.AttrbuteKeyNamespace;
import org.ala.tcp_feign_common.enums.TcpFeignCloseTypeEnums;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_server.context.TcpFeignServerContext;
import org.slf4j.Logger;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;


/**
 * 等待登录消息队列
 *
 * @author 骆毅(ala)
 * @date 2024年4月19日
 */
public class WaitForLoginQueue {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "server");

	
	/**
	 * 等待登录消息队列
	 */
	protected LinkedList<Channel> queue = null;
	/**
	 * 检测间隔
	 * <p>	单位：毫秒
	 * <p>	默认1分钟
	 */
	protected long interval = 60 * 1000l;
	/**
	 * 
	 */
	protected ScheduledExecutorService scheduled;
	
	
	/**
	 * 初始化
	 */
	public void init(long interval) {
		this.interval = interval;
		queue = new LinkedList<>();
		
		//	开始检测线程
		scheduled = Executors.newScheduledThreadPool(1);
		scheduled.scheduleAtFixedRate(() -> check(), interval/2, interval/2, TimeUnit.MILLISECONDS);
	}
	/**
	 * 检测方法
	 */
	protected void check() {
//		log.info("[WaitForLoginQueue check] 开始未登录检测");
		
		//	从队首挖channel
		Long now = System.currentTimeMillis();
		while (!queue.isEmpty()) {
			Channel channel = queue.peekFirst();
			//	检测其是否到了最大等待时间
			Long connectTimestamp = (Long)channel.attr(AttributeKey.valueOf(AttrbuteKeyNamespace.CONNECT_TIMESTAMP)).get();
			Long diff = now - connectTimestamp;
			//	如果还没有超过最大等待时间，那后面的都没有超过（queue本身是按connectTimestamp升序的）
			if (diff < interval) {break;}
			
			channel = queue.pollFirst();
			//	检测其登录状态
			Boolean login = (Boolean)channel.attr(AttributeKey.valueOf(AttrbuteKeyNamespace.LOGIN)).get();
			if (login == null || !login) {
				log.info("[WaitForLoginQueue check] 检测到登录超时的连接，即将关闭. remoteAddress:" + channel.remoteAddress());
				
				TcpFeignServerContext.instance().closeClient(channel, TcpFeignCloseTypeEnums.LOGIN_ERROR);
			}
		}
	}
	
	
	/**
	 * 放入channel
	 */
	public void append(Channel channel) {
		queue.addLast(channel);
	}
	
}
